/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package testcode;

/**
 *
 * @author Vitamin
 */
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import javax.media.*;
import javax.media.control.*;
import javax.media.format.*;
import javax.media.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.media.datasink.*;
import javax.media.protocol.*;
import java.awt.event.*;
import com.sun.image.codec.jpeg.*;

class FrameGrab2
{
public static void main(String[] args) throws Exception
{
boolean saved;
CaptureDeviceInfo webCamDeviceInfo = null;
MediaLocator ml = null;
Dimension imageSize = null;
FormatControl formatControl = null;
VideoFormat currentFormat = null;
Format[] videoFormats = null;
Player player=null;
// Create capture device
CaptureDeviceInfo deviceInfo =CaptureDeviceManager.getDevice("vfw:Microsoft WDM Image Capture(Win32):0");

try
{
player =Manager.createRealizedPlayer(deviceInfo.getLocator());
player.start();
Format[] formats = deviceInfo.getFormats();
currentFormat = (RGBFormat)formats[3]; // This was the key


formatControl = (FormatControl)player.getControl
( "javax.media.control.FormatControl" );
formatControl.setFormat ( currentFormat );
Format currFormat = formatControl.getFormat();
player.start();

// Wait a few seconds for camera to initialise (otherwise img==null)

Thread.sleep(5000);

// Grab a frame from the capture device
FrameGrabbingControl frameGrabber =
(FrameGrabbingControl)player.getControl("javax.media.control.FrameGrabbingControl");
Buffer buf = frameGrabber.grabFrame();

// Convert frame to an buffered image so it can be processed and saved
Image img = (new BufferToImage((VideoFormat)buf.getFormat()).createImage(buf));

BufferedImage buffImg = new BufferedImage(img.getWidth(null),
img.getHeight(null), BufferedImage.TYPE_INT_RGB);

Graphics2D g = buffImg.createGraphics();
g.drawImage(img, null, null);

FileOutputStream out = null;


try
{
out = new FileOutputStream ( "C:/Users/Pictures/Test1.jpg" );
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder
( out );
JPEGEncodeParam param =
encoder.getDefaultJPEGEncodeParam ( buffImg );
param.setQuality ( 1.0f, false ); // 100% high quality setting, no compression
encoder.setJPEGEncodeParam ( param );
encoder.encode ( buffImg );
out.close();
saved = true;
}
catch ( Exception ex )
{
System.out.println ("Error saving JPEG : " +
ex.getMessage() );
}



// Stop using webcam
player.stop();
player.close();
player.deallocate();
player = null;
System.exit(0);

}catch (Exception e)
{}
}
}